package com.liuyi.netty.mqtt.channel;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * Mqtt Netty ChannelInitializer （通道初始化，针对pipeline）
 *
 * @author Mr.Fmy
 * @since 2021-08-19
 */
public class MqttChannelInitializer extends ChannelInitializer<SocketChannel> {

    /**
     * 初始化通道
     */
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        //pipeline管道获取
        final ChannelPipeline pipeline = socketChannel.pipeline();
        //心跳处理
        pipeline.addLast("timeout", new IdleStateHandler(30, 0, 20,
                TimeUnit.SECONDS));
        //Mqtt 解码器
        pipeline.addLast(new MqttDecoder(81920));
        //Mqtt 编码器
        pipeline.addLast(MqttEncoder.INSTANCE);
        //自定义 Mqtt消息处理
        pipeline.addLast(new MqttChannelHandler());
    }
}
